package com.kugou.miniapp.utils;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.kugou.miniapp.controller.MusicController;
import com.kugou.miniapp.domain.LikeAndUserList;
import com.kugou.miniapp.domain.Users;
import com.kugou.miniapp.service.MusicService;
import com.kugou.miniapp.service.UserService;
import lombok.Data;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @Author：hbt
 * @Description：
 * @Date： created in 15:56 2019/5/13
 */

@Component
@ServerEndpoint(value = "/global_socket/{userId}")
public class GlobalSocket {
//    private Logger logger = LoggerFactory.getLogger(this.getClass());

    //用于保存socket的集合容器
    @JsonIgnore
    public static CopyOnWriteArrayList<GlobalSocket> socket_list = new CopyOnWriteArrayList<GlobalSocket>();
    //会话
    @JsonIgnore
    public Session session;

    public String getUser_id() {
        return user_id;
    }

    public void setUser_id(String user_id) {
        this.user_id = user_id;
    }

    public String user_id;

    public static MusicService musicService;

    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session) throws Exception {
        synchronized (GlobalSocket.class){
            userId = userId.substring(0, 20);
//            logger.info("现在来匹配的客户id："+session.getId()+"用户名："+userId);
            System.out.println("global socket :"+userId+" start "+Thread.currentThread().getName());
            //做一些初始化工作
            this.user_id = userId;
            this.session = session;
            //通过userid获取music_list
            musicService = (MusicService) SpringBootBeanUtil.getBean(MusicService.class);
            UserService userService = (UserService)SpringBootBeanUtil.getBean(UserService.class);
            //通过userid设置avatar和nick_name
            Users u = userService.getUserByUserId(userId);
            if(u == null){
                throw new Exception("不存在该用户："+userId);
            }

            //如果已经在socket_list存在userid，那么直接close掉并return
            for (int i = 0; i < socket_list.size(); i++) {
                if (socket_list.get(i).user_id.equals(userId)){
                    System.out.println(userId+"：global重复连接");
                    try {

                        this.session.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    throw new Exception(userId+":global重复连接");
//                    return;
                }
            }
            //把自己的信息加入到list当中去
            socket_list.add(this);
            System.out.println("global socket 连接成功");
        }//synchronized end
    }//onOpen end




    @OnError
    public void onError(Session session, Throwable error) {
//        logger.info("服务端发生了错误"+error.getMessage());
        System.out.println("global socket 发生 error:"+error.getMessage());

        //error.printStackTrace();
    }
    /**
     * 连接关闭
     */
    @OnClose
    public void onClose() throws IOException {
        synchronized (GlobalSocket.class){
            System.out.println("global socket 发生 close");
            GlobalSocket.socket_list.remove(this);

            String remove_key = "uuu54覆盖35";
            Users u_remove = null;
            for (String mid: MusicController.map_list.keySet()){
                LikeAndUserList likeAndUserList = MusicController.map_list.get(mid);
                List<Users> users_list = likeAndUserList.getUser_list();
                for (int i = 0; i < users_list.size(); i++) {
                    Users u = users_list.get(i);
                    if (u.getUser_id().equals(user_id)){
                        u_remove = u;
                        if (users_list.size() == 1){
                            remove_key = mid;
                            break;
                        }
                    }
                }
                if (u_remove != null){
                    users_list.remove(u_remove);
                }
            }
            if (!remove_key.equals("uuu54覆盖35")){
                System.out.println("remove map_list's key:"+remove_key);
                MusicController.map_list.remove(remove_key);
            }
        }
    }//onClose end


    public void sendMessageTo(String message, String TouserId) throws IOException {
    }

    public void sendMessageAll(String message,String FromuserId) throws IOException {
    }


}
